//package com.test.learnkotlin.ui.activity
//
//import android.Manifest
//import android.content.Context
//import android.content.Intent
//import android.graphics.Color
//import android.graphics.drawable.ColorDrawable
//import android.media.MediaScannerConnection
//import android.net.Uri
//import android.os.Build
//import android.util.Log
//import android.util.Size
//import android.view.SoundEffectConstants
//import android.view.ViewGroup
//import android.webkit.MimeTypeMap
//import android.widget.ImageView
//import android.widget.PopupWindow
//import androidx.camera.core.*
//import androidx.camera.lifecycle.ProcessCameraProvider
//import androidx.camera.view.PreviewView
//import androidx.core.content.ContextCompat
//import androidx.core.net.toFile
//import com.google.common.util.concurrent.ListenableFuture
//import com.test.learnkotlin.BR
//import com.test.learnkotlin.R
//import com.test.learnkotlin.base.BaseActivity
//import com.test.learnkotlin.databinding.ActivityCameraxBinding
//import com.test.learnkotlin.main
//import com.test.learnkotlin.utils.LogUitls
//import com.test.learnkotlin.viewmodel.TestCameraXViewModel
//import java.io.File
//import java.text.SimpleDateFormat
//import java.util.*
//import java.util.concurrent.ExecutorService
//import java.util.concurrent.Executors
//
///*
//
//关于Http协议的知识总结
//https://sunnyboy.blog.csdn.net/article/details/104475472?spm=1001.2101.3001.6650.3&utm_medium=distribute.pc_relevant.none-task-blog-2%7Edefault%7EBlogCommendFromBaidu%7ERate-3-104475472-blog-107740275.t5_layer_targeting_s_randoms&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2%7Edefault%7EBlogCommendFromBaidu%7ERate-3-104475472-blog-107740275.t5_layer_targeting_s_randoms&utm_relevant_index=4
//
//Android camera2 实现相机预览及获取预览帧数据流
//https://blog.csdn.net/ganfanzhou/article/details/83721750?spm=1001.2101.3001.6650.3&utm_medium=distribute.pc_relevant.none-task-blog-2%7Edefault%7ECTRLIST%7ERate-3-83721750-blog-122143560.pc_relevant_aa&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2%7Edefault%7ECTRLIST%7ERate-3-83721750-blog-122143560.pc_relevant_aa&utm_relevant_index=5
//
//Camera2】Android Camera2 综述
//https://blog.csdn.net/Scott_S/article/details/122143560
//
//Android Media 07 --- Camera2
//https://www.jianshu.com/p/a06883b8f713
//
//Android Camera2 教程 · 第四章 · 拍照
//https://www.jianshu.com/p/2ae0a737c686
//
//
//CameraX 架构
//https://developer.android.google.cn/training/camerax/architecture#kotlin
//
//CameraX
//https://developer.android.google.cn/jetpack/androidx/releases/camera?hl=en
//
//使用Camera X遇到的坑_OnPause时没有释放相机导致回来时黑屏
//https://blog.csdn.net/cjzjolly/article/details/124293800
//
//
//本文使用下面链接
//Android 使用CameraX实现预览/拍照/录制视频/图片分析/对焦/切换摄像头等操作
//https://blog.csdn.net/EthanCo/article/details/125603671
//
// */
//class TestCameraXActivity : BaseActivity<TestCameraXViewModel, ActivityCameraxBinding>() {
//    private lateinit var mCameraProvider: ProcessCameraProvider
//    private var mPreview: Preview? = null
//    private var mCamera: Camera? = null
//    val CamearRequestCode = 1001
//    private lateinit var mTakePhotoExecutor: ExecutorService
//
//    private var mImageCapture: ImageCapture? = null
//
//    private var mCameraSelector = CameraSelector.DEFAULT_BACK_CAMERA
//
//
//    override fun getContentLayoutId(): Int = R.layout.activity_camerax
//
//    override fun variableId(): Int = BR.mTestCameraXViewModel
//
//    override fun initView() {
//        super.initView()
////        mTakePhotoExecutor = Executors.newSingleThreadExecutor()
//        mTakePhotoExecutor = Executors.newFixedThreadPool(6)
//        checkPermissions()
//
////        setUpCamera(mDataBinding.previewView)
//    }
//
//
//    private fun checkPermissions() {
////        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
//            requestPermissions(
//                arrayOf(
//                    Manifest.permission.CAMERA,
//                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
//                    Manifest.permission.READ_EXTERNAL_STORAGE,
//                    Manifest.permission.RECORD_AUDIO
//                ), CamearRequestCode
//            )
////        }
//    }
//
//    private fun showTapView(x: Int, y: Int) {
//        val popupWindow = PopupWindow(
//            ViewGroup.LayoutParams.WRAP_CONTENT,
//            ViewGroup.LayoutParams.WRAP_CONTENT
//        )
//        val imageView = ImageView(this)
//        imageView.setImageResource(R.drawable.shape_white_stroke)
//        popupWindow.contentView = imageView
//        popupWindow.showAsDropDown(mDataBinding.previewView, x, y)
//        mDataBinding.previewView.postDelayed({ popupWindow.dismiss() }, 600)
//        mDataBinding.previewView.playSoundEffect(SoundEffectConstants.CLICK)
//    }
//
//
//    override fun initEvent() {
//        super.initEvent()
//
//        mDataBinding.previewView.setOnTouchListener{view,event ->
//            val action  = FocusMeteringAction.Builder(mDataBinding.previewView.meteringPointFactory.createPoint(event.x,event.y)).build()
//
//            showTapView(event.x.toInt(), event.y.toInt())
//            mCamera?.getCameraControl()?.startFocusAndMetering(action)
//
//            true
//        }
//
//        mDataBinding.tvSwitchPicture.setOnClickListener {
//
//            mCameraSelector =  if (mCameraSelector == CameraSelector.DEFAULT_BACK_CAMERA)  CameraSelector.DEFAULT_FRONT_CAMERA else  CameraSelector.DEFAULT_BACK_CAMERA
//            bindPreview(mCameraProvider, mDataBinding.previewView, mCameraSelector)
//        }
//
//        mDataBinding.tvTakePicture.setOnClickListener {
//
//            mImageCapture?.let {
//
//                val photoFile = createFile(getOutputDirectory(this), FILENAME, PHOTO_EXTENSION)
//                LogUitls.i("photoFile:$photoFile")
//                val metadata  = ImageCapture.Metadata().apply {
////                    isReversedHorizontal = lensFacing == CameraSelector.LENS_FACING_FRONT
//                }
//
//                val outputOptions = ImageCapture.OutputFileOptions.Builder(photoFile)
//                    .setMetadata(metadata)
//                    .build()
//
//                val mainExecutor =  ContextCompat.getMainExecutor(this)
//
//                //拍照没有保存文件
////                it.takePicture( mainExecutor,object : ImageCapture.OnImageCapturedCallback(){
////                    override fun onCaptureSuccess(image: ImageProxy) {
////                        super.onCaptureSuccess(image)
////
////                        LogUitls.i("onCaptureSuccess 拍照成功 宽： ${image.width} ，高： ${image.height}")
////
////                    }
////
////                    override fun onError(exception: ImageCaptureException) {
////                        super.onError(exception)
////                        LogUitls.i("takePicture 发生异常：${exception}")
////
////                    }
////                })
//
//
//                //拍照并保存到本地存储
//                it.takePicture( outputOptions, mainExecutor,object : ImageCapture.OnImageSavedCallback{
//                    override fun onImageSaved(outputFileResults: ImageCapture.OutputFileResults) {
//                        val savedUri = outputFileResults.savedUri ?: Uri.fromFile(photoFile)
//
//                        LogUitls.i("onCaptureSuccess 拍照成功 savedUri： $savedUri")
//
//                        // // Implicit broadcasts will be ignored for devices running API level >= 24
//                        // so if you only target API level 24+ you can remove this statement
//
//                        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
//                            application.sendBroadcast(Intent(android.hardware.Camera.ACTION_NEW_PICTURE, savedUri))
//                        }
//
//
//
//                        // If the folder selected is an external media directory, this is
//                        // unnecessary but otherwise other apps will not be able to access our
//                        // images unless we scan them using [MediaScannerConnection]
//                        val mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(savedUri.toFile().extension)
//                        MediaScannerConnection.scanFile(application, arrayOf(savedUri.toFile().absolutePath), arrayOf(mimeType)) { _, uri ->
//                            LogUitls.i("Image capture scanned into media store: $uri")
//                        }
//
//
//                    }
//
//                    override fun onError(exception: ImageCaptureException) {
//                        LogUitls.i("takePicture 发生异常：${exception}")
//                    }
//                })
//
//                //让画面闪一下，营造拍照的感觉
//                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
//                    // Display flash animation to indicate that photo was captured
//                    mDataBinding.root.postDelayed({
//                        mDataBinding.root.foreground = ColorDrawable(Color.WHITE)
//                        mDataBinding.root.postDelayed(
//                            { mDataBinding.root.foreground = null }, 50L
//                        )
//                    }, 100L)
//                }
//            }
//        }
//    }
//
//    //拍照并保存到本地存储
//    private fun createFile(baseFolder: File, format: String, extension: String) = File(baseFolder,SimpleDateFormat(format, Locale.US).format(System.currentTimeMillis())+extension)
//
//    fun getOutputDirectory(context: Context): File{
//        val appContext = context.applicationContext
//        val mediaDir  = context.externalMediaDirs.firstOrNull()?.let {
//            File(it, appContext.resources.getString(R.string.app_name)).apply { mkdirs() }
//        }
//
//        return if (mediaDir != null && mediaDir.exists()) mediaDir else appContext.filesDir
//    }
//
//    companion object {
//        private const val FILENAME = "yyyy-MM-dd-HH-mm-ss-SSS"
//        private const val PHOTO_EXTENSION = ".jpg"
//    }
//
//    private fun setUpCamera(previewView: PreviewView,) {
//        val cameraProviderFuture: ListenableFuture<ProcessCameraProvider> = ProcessCameraProvider.getInstance(this)
//        cameraProviderFuture.addListener({
//
//            try {
//                LogUitls.i("cameraProviderFuture  bindPreview")
//                mCameraProvider = cameraProviderFuture.get()
//                bindPreview(mCameraProvider, previewView, mCameraSelector)
//            } catch (e: Exception) {
//                LogUitls.i("cameraProviderFuture 发生异常：${e}")
//            }
//
//        }, ContextCompat.getMainExecutor(this))
//    }
//
//    private fun bindPreview(cameraProvider: ProcessCameraProvider,previewView: PreviewView, cameraSelector : CameraSelector){
//        //图像分析 : ImageAnalysis.java
//        val imageAnalysis  = ImageAnalysis.Builder().setTargetResolution(Size(1280, 720))
//            .setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST)
//            .build()
//
//        imageAnalysis.setAnalyzer(mTakePhotoExecutor, {
//            val rotationDegrees  = it.imageInfo.rotationDegrees
//            //在这里处理图片的解析，比如解析成二维码之类的
//
//            it.close()
//        })
//
//        //拍照 : ImageCapture.java
//        mImageCapture  = ImageCapture.Builder().setCaptureMode(ImageCapture.CAPTURE_MODE_MINIMIZE_LATENCY)
//            //.setTargetAspectRatio(screenAspectRatio)
//            //.setTargetRotation(binding.previewView.display.rotation)
//            .build()
//
//
//
//
//
//        //解除所有绑定，防止CameraProvider重复绑定到Lifecycle发生异常
//        cameraProvider.unbindAll()
//        mPreview = Preview.Builder().build()
////        mCamera = cameraProvider.bindToLifecycle(this, CameraSelector.DEFAULT_BACK_CAMERA, mPreview)
////        mCamera = cameraProvider.bindToLifecycle(this, CameraSelector.DEFAULT_BACK_CAMERA, mPreview,imageAnalysis)
//        mCamera = cameraProvider.bindToLifecycle(this, cameraSelector, mPreview,mImageCapture)
//        LogUitls.i("mPreview = ${mPreview == null}")
//        mPreview?.setSurfaceProvider(previewView.surfaceProvider)
//    }
//
//    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
//        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
//        //android 权限开启回调
//        //https://www.csdn.net/tags/NtDaggxsNzAzMjQtYmxvZwO0O0OO0O0O.html
//
//        var granted = true
//
//        grantResults.map {
//            LogUitls.i("授权结果：$it")
//            if (it == -1) {
//                granted = false
//            }
//        }
//
//        if (granted) {
//            LogUitls.i("全部授权 setUpCamera")
//
//            setUpCamera(mDataBinding.previewView)
//        }else{
//            LogUitls.i("重新申请权限 checkPermissions")
//
//            checkPermissions()
//        }
//
//        LogUitls.i("requestCode = $requestCode , permissions = ${permissions.toList()} , grantResults = ${grantResults.toList()}")
//        //requestCode = 1001 , permissions = [android.permission.CAMERA, android.permission.WRITE_EXTERNAL_STORAGE, android.permission.READ_EXTERNAL_STORAGE, android.permission.RECORD_AUDIO] , grantResults = [-1, 0, 0, -1]
//        //grantResults: -1表示 拒绝， 0： 表示同意
//    }   //[-1, -1, -1, -1] 全部拒绝，
//        //[0, 0, 0, 0] 全部同意
//}